package com.horay.springclouddemo.feign.nacos.controller;

import com.horay.springclouddemo.feign.nacos.service.NacosClientService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.stream.Collectors;

@RestController
public class NacosFeignController {

	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private NacosClientService nacosClientService;

	@Autowired
	private DiscoveryClient discoveryClient;

	// @PostConstruct
	// public void init() {
	// restTemplate1.setErrorHandler(new ResponseErrorHandler() {
	// @Override
	// public boolean hasError(ClientHttpResponse response) throws IOException {
	// return false;
	// }
	//
	// @Override
	// public void handleError(ClientHttpResponse response) throws IOException {
	// System.err.println("handle error");
	// }
	// });
	// }

	@GetMapping("/echo-rest/{str}")
	public String rest(@PathVariable String str) {
		return restTemplate.getForObject("http://nacos-client/echo/" + str,
				String.class);
	}

	@GetMapping("/index")
	public String index() {
		return restTemplate.getForObject("http://nacos-client", String.class);
	}

	@GetMapping("/test")
	public String test() {
		return restTemplate.getForObject("http://nacos-client/test", String.class);
	}

	@GetMapping("/sleep")
	public String sleep() {
		return restTemplate.getForObject("http://nacos-client/sleep", String.class);
	}

	@GetMapping("/notFound-feign")
	public String notFound() {
		return nacosClientService.notFound();
	}

	@GetMapping("/divide-feign")
	public String divide(@RequestParam Integer a, @RequestParam Integer b) {
		return nacosClientService.divide(a, b);
	}

	@GetMapping("/divide-feign2")
	public String divide(@RequestParam Integer a) {
		return nacosClientService.divide(a);
	}

	@GetMapping("/echo-feign/{string}")
	public String feign(@PathVariable String string) {
		return nacosClientService.echo(string);
	}

	@GetMapping("/services/{service}")
	public Object client(@PathVariable String service) {
		return discoveryClient.getInstances(service);
	}

	@GetMapping("/services")
	public Object services() {
		return discoveryClient.getServices();
	}

    @GetMapping("/services/instances/{service}")
    public Object instances(@PathVariable String service) {
        List<ServiceInstance> instances = discoveryClient.getInstances(service);
        return instances.stream().map(instance -> StringUtils.join(instance.getHost(), ":", String.valueOf(instance.getPort()))).collect(Collectors.toList());
    }
}
